<template>
  <div style="margin-bottom: 6px" class="opera-header">
    <el-button type="warning" plain @click="dialogAddGroup = true">新增任务组</el-button>
  </div>

  <template v-for="(group,name) in task_group_info['taskgroups']">
    <el-dropdown split-button type="primary">
      {{ group.name }}
      <template #dropdown>
        <el-dropdown-menu>
          <el-dropdown-item @click="AddTask(group)">新增</el-dropdown-item>
          <el-dropdown-item @click="MoveUp(group)">上移</el-dropdown-item>
          <el-dropdown-item @click="MoveDown(group)">下移</el-dropdown-item>
          <el-dropdown-item @click="EditGroup(group)">编辑</el-dropdown-item>
          <el-dropdown-item @click="DeleteGroup(group)">删除</el-dropdown-item>
        </el-dropdown-menu>
      </template>
    </el-dropdown>

    <div id="tasklist">
      <ul class="tasks">
        <li v-for="(item,index) in group.tasks">
          <div id="task">
            <div @click="ChangeTask(item,group.name)"><span :class="{ active: item.isActive }">{{ item.name }}</span></div>
            <div class="child">
              <div class="task_opation">
                <el-icon @click="MoveUpTask(group,item)" class="o">
                  <top/>
                </el-icon>
                <el-icon @click="MoveDownTask(group,item)" class="o">
                  <Bottom/>
                </el-icon>
                <el-icon @click="DeleteTask(group,item)" class="o">
                  <close/>
                </el-icon>
              </div>
            </div>
          </div>
        </li>
      </ul>
    </div>
  </template>


  <el-dialog v-model="dialogGroup" title="任务组策略" width="30%" :before-close="handleClose">
    <el-form label-position="top">
      <el-form-item label="任务组名称">
        <el-input v-model="TaskGroup.name"></el-input>
      </el-form-item>

      <el-form-item label="运行策略">
        <el-select v-model="TaskGroup.strategy" placeholder="运行策略">
          <el-option v-for="item in options" :key="item" :label="item" :value="item"/>
        </el-select>
      </el-form-item>

      <el-form-item label="运行方式">
        <el-select v-model="TaskGroup.runway" placeholder="运行方式">
          <el-option v-for="item in runway_oper" :key="item" :label="item" :value="item"/>
        </el-select>
      </el-form-item>
    </el-form>

    <template #footer>
      <span class="dialog-footer">
        <el-button type="primary" @click="handleClose">
          确认
        </el-button>
      </span>
    </template>
  </el-dialog>

  <el-dialog v-model="dialogAddGroup" title="新增任务组" width="30%" :before-close="handleClose">
    <el-form label-position="top" :rules="rules" :model="form1" ref="ruleFormRef">
      <el-form-item label="任务组名称" prop="name">
        <el-input v-model="form1.name"></el-input>
      </el-form-item>
    </el-form>

    <template #footer>
      <span class="dialog-footer">
        <el-button type="primary" @click="AddGroup(ruleFormRef)">
          确认
        </el-button>
      </span>
    </template>
  </el-dialog>

  <el-dialog v-model="dialogAddTask" title="新增任务" width="30%" :before-close="handleClose">
    <el-form label-position="top" :rules="rules2" :model="form2" ref="ruleFormRef">
      <el-form-item label="任务名称" prop="name">
        <el-input v-model="form2.name"></el-input>
      </el-form-item>

      <el-form-item label="任务类型" prop="task_type">
        <el-select v-model="form2.task_type" placeholder="请选择任务类型">
          <el-option v-for="item in type_list" :key="item" :label="item" :value="item"/>
        </el-select>
      </el-form-item>
    </el-form>


    <template #footer>
      <span class="dialog-footer">
        <el-button type="primary" @click="SubAddTask(ruleFormRef)">
          确认
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import {onMounted, reactive, ref} from 'vue'
import {ElMessage, ElMessageBox, FormInstance, FormRules} from "element-plus";
import {checkSpecialKey} from '@/utils/str'

const dialogGroup = ref(false)
const dialogAddGroup = ref(false)
const dialogAddTask = ref(false)
const TaskGroup = ref(null)

const runway_oper = ref(["串行", "并行"])
const options = ["总是运行", "失败运行", "成功运行"]
const type_list = ref(["监控", "API", "自动化用例", "SHELL命令行"])

const prop = defineProps(['data'])
const emit = defineEmits(['UpdateTask'])
const task_group_info = ref({})
task_group_info.value = prop.data

interface RuleForm {
  name: string
}

const ruleFormRef = ref<FormInstance>()

const EditGroup = (group) => {
  TaskGroup.value = group
  dialogGroup.value = true
}

const rules = reactive(<FormRules<RuleForm>>({
  name: [
    {required: true, message: '请输入任务组名', trigger: 'blur'},
    {min: 3, max: 16, message: '长度在3到16之间', trigger: 'blur'},
    {validator: checkSpecialKey, message: "不能包含特殊字符,请使用_分割字符", trigger: "blur"}
  ]
}))

const rules2 = reactive(<FormRules<RuleForm>>({
  name: [
    {required: true, message: '请输入任务名', trigger: 'blur'},
    {min: 3, max: 16, message: '长度在3到16之间', trigger: 'blur'},
    {validator: checkSpecialKey, message: "不能包含特殊字符,请使用_分割字符", trigger: "blur"},
  ],
  task_type: [
    {required: true, message: '请选择任务类型', trigger: 'blur'},
  ]
}))

const CheckSameName = (groups, str) => {
  for (var i in groups) {
    if (groups[i]['name'] == str) {
      ElMessage({
        showClose: true,
        message: "该名称已存在",
        type: 'error'
      })
      return false
    }
  }
  return true
}

const form1 = reactive(<RuleForm>({
  name: ''
}))

const form2 = reactive(<RuleForm>({
  name: '',
  task_type: ''
}))

const AddGroup = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  if (!CheckSameName(task_group_info.value['taskgroups'], form1.name)) {
    return
  }
  await formEl.validate((valid, fields) => {
    if (valid) {
      task_group_info.value['taskgroups'].push(
          {
            "name": form1.name,
            "runway": "串行",
            "tasks": []
          },
      )
      dialogAddGroup.value = false
      return
    } else {
      return;
    }
  })
}

const ChangeGroupStaskByTask = async (group) => {
  var check_list = await group['checklist']
  var tasks = group.tasks
  var f = 0
  var t = 0

  for (var i in tasks) {
    if (tasks[i].status == true) {
      check_list.push(parseInt(i))
      t++
    } else {
      f++
    }
  }
  if (tasks.length == t) {
    group['status'] = true
    group['isIndeterminate'] = false
  } else if (group.tasks.length == f) {
    group['status'] = false
    group['isIndeterminate'] = false
  } else {
    group['status'] = false
    group['isIndeterminate'] = true
  }
}


onMounted(() => {
  for (var i in task_group_info.value['taskgroups']) {
    var group = task_group_info.value['taskgroups'][i]
    group['checklist'] = []
    group['status'] = false
    group['isIndeterminate'] = false
    ChangeGroupStaskByTask(group)
  }
})

const mobile = (arr, i, num) => {
  arr.splice(i, 0, arr.splice(i + num, 1)[0])
}
const MoveUp = (group) => {
  if (task_group_info.value['taskgroups'].indexOf(group) != 0) {
    mobile(task_group_info.value['taskgroups'], task_group_info.value['taskgroups'].indexOf(group), -1)
  }
}
const MoveDown = (group) => {
  if (task_group_info.value['taskgroups'].indexOf(group) != task_group_info.value['taskgroups'].length - 1) {
    mobile(task_group_info.value['taskgroups'], task_group_info.value['taskgroups'].indexOf(group), 1)
  }
}

const DeleteGroup = (group) => {
  ElMessageBox.confirm("确认要删除此任务组吗?").then(() => {
    task_group_info.value['taskgroups'] = task_group_info.value['taskgroups'].filter((item) => item != group)
  })
}

const DeleteTask = (group, task) => {
  ElMessageBox.confirm("确认要删除此任务吗?").then(() => {
    if (group.tasks.length == 1) {
      DeleteGroup(group)
    } else {
      group.tasks.splice(task, 1)
    }
  })
}


const cur_group = ref(null)
const AddTask = (group) => {
  cur_group.value = group
  dialogAddTask.value = true
}

const SubAddTask = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  if (!CheckSameName(cur_group.value.tasks, form2.name)) {
    return
  }
  await formEl.validate((valid, fields) => {
    if (valid) {
      let new_task = {"name": form2.name, testcases: []}
      cur_group.value.tasks.push(new_task)
      dialogAddTask.value = false
      return
    } else {
      return;
    }
  })
}

const MoveUpTask = (group, task) => {
  for (var i in group.tasks) {
    if (group.tasks[i].name == task.name) {
      if (group.tasks.indexOf(task) != 0) {
        mobile(group.tasks, group.tasks.indexOf(task), -1)
      }
    }
  }
}
const MoveDownTask = (group, task) => {
  for (var i in group.tasks) {
    if (group.tasks[i].name == task.name) {
      if (group.tasks.indexOf(task) != (group.tasks.length - 1)) {
        mobile(group.tasks, group.tasks.indexOf(task), 1)
      }
    }
  }
}
const ChangeTask = async (item,group_name) => {
  if (task_group_info.value['cur_task'] != null) {
    task_group_info.value['cur_task'].isActive = false
  }
  task_group_info.value['cur_task'] = await item
  task_group_info.value['cur_group'].name = group_name
  item.isActive = true
  emit("UpdateTask");
}

const handleClose = () => {
  dialogAddGroup.value = false
  dialogGroup.value = false
  dialogAddTask.value = false
}
</script>
<style scoped>
.strategy, .runway {
  padding-right: 8px;
  font-size: 16px;
  font-weight: bold;
  color: #000a00;
}

:deep(.el-dialog__body) + div {
  margin-bottom: 12px !important;
}

.task_opation {
  display: inline;
  font-size: 12px;
}

#task {
  display: grid;
  grid-template-columns: 5fr 3fr;
  margin-bottom: 4px;
  width: 100%;
  padding: 0;
  align-items: center;
  margin-left: 10px
}

.child {
  display: none;
}

.o:hover {
  color: green;
  font-weight: bold;
}

#task:hover .child {
  display: block;
  padding-right: 10px;
}

#task div:nth-child(1) {
  margin-top: 6px
}

#task div {
  font-size: 15px;
  padding-left: 8px;
  margin-bottom: 4px;
  color: #575252;
}

.tasks li:last-child {
  margin-bottom: 8px
}

#task .child .task_opation .el-icon {
  font-size: 12px;
  padding-right: 4px;
}

.opera-header .el-button {
  padding: 10px;
}

.active {
  color: #f82d2d !important;
  border-bottom: #d7d4ce solid; /* 添加下划线效果 */
  border-width: 4px; /* 设置下划线的粗细为2像素 */
  border-radius: 2px;
}
</style>